import java.util.ArrayList;
import java.util.List;

public class Solution1609 {

    boolean ans=true;

    static class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
    }

    public boolean isEvenOddTree(TreeNode root) {
        List<Integer> record=new ArrayList<>();
        dfs(root,0,record);
        return ans;
    }

    public void dfs(TreeNode node,int k,List<Integer> record){
        if (node==null || ans==false){
            return;
        }
        if (record.size()<=k){
            record.add(k%2==0?Integer.MIN_VALUE:Integer.MAX_VALUE);
        }
        if (k%2==0 && node.val<=record.get(k)|| k%2==1 && node.val>=record.get(k) || k%2==node.val%2) {
            ans = false;
            return;
        }
        record.set(k,node.val);
        dfs(node.left,k+1,record);
        dfs(node.right,k+1,record);
    }

    public static void main(String[] args) {
        TreeNode root=new TreeNode(1,new TreeNode(10,new TreeNode(3,new TreeNode(12),new TreeNode(8)),null),new TreeNode(4,new TreeNode(7,new TreeNode(6),null),new TreeNode(9,null,new TreeNode(2))));
        System.out.println(new Solution1609().isEvenOddTree(root));
    }
}
